package com.sgb.kjwl.viewmodel.self.publish;

import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.self.AddProjectEntity;
import com.sgb.kjwl.model.entity.self.ProjectTarRateEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.view.ui.activity.self.publish.AddProjectActivity;
import com.sgb.kjwl.view.widget.TeamMultiPopWindow;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddProjectModel extends BaseViewModel implements TeamMultiPopWindow.FilterResultClick, TeamMultiPopWindow.IItemClick {

    public ObservableField<AddProjectEntity> addProjectEntity = new ObservableField<>(new AddProjectEntity());

    private AddProjectActivity mActivity;
    private SelfRepertory repertory;

    private TeamMultiPopWindow mPopWindow;
    private List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> mJobData;

    public AddProjectModel(AddProjectActivity activity, SelfRepertory repertory) {
        mActivity = activity;
        this.repertory = repertory;
    }

    public void getAddressModel() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getCode().equals("200"))
                    mActivity.showAddressPop(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void addProjectModel() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().addNewProject(addProjectEntity.get()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.BeckProjectActivity();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void detailProject(String id) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().detailProject(id).enqueue(new Callback<BaseEntity<AddProjectEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<AddProjectEntity>> call, Response<BaseEntity<AddProjectEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.displayData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<AddProjectEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void getCategoryData(String cid, View view) {
        Call<BaseEntity<List<PickSelectEntity>>> call;
        if (mPopWindow == null) {
            DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
            APIManager.getInstance().getUserAPI().findJobCategoryListTree(repertory.getAreaCode()).enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>() {
                @Override
                public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> response) {
                    DialogHelper.dismissProgressDialog();
                    if (response.body() == null || response.body().getState() == null) {
                        return;
                    }
                    if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                        mJobData = response.body().getData();
                        List<PickSelectEntity> list = new ArrayList<>();
                        for (PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>> mJobDatum : mJobData) {
                            PickSelectEntity entity = new PickSelectEntity();
                            entity.setNo(mJobDatum.getNo());
                            entity.setProjectscale(mJobDatum.getProjectscale());
                            list.add(entity);
                        }
                        updateData(list, view);
                    }
                }

                @Override
                public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Throwable t) {
                    DialogHelper.dismissProgressDialog();
                }
            });
        }
    }

    private void updateData(List<PickSelectEntity> data, View view) {
        if (data == null || data.size() == 0) {
            return;
        }
        if (mPopWindow == null) {
            //初始化筛选
            mPopWindow = new TeamMultiPopWindow(mActivity);
            mPopWindow.setFilterResultClick(this);
            mPopWindow.onItemClick(this);
        }
        switch (mPopWindow.getType()) {
            case TeamMultiPopWindow.TYPE_DEFAULT:
                mPopWindow.setData1(data);
                break;
            case TeamMultiPopWindow.TYPE_TWO:
                mPopWindow.setData2(data);
                break;
            case TeamMultiPopWindow.TYPE_THR:
                mPopWindow.setData3(data);
                break;
            case TeamMultiPopWindow.TYPE_FOU:
                mPopWindow.setData4(data);
                break;
            case TeamMultiPopWindow.TYPE_FIV:
                mPopWindow.setData5(data);
                break;
            case TeamMultiPopWindow.TYPE_SIX:
                mPopWindow.setData6(data);
                break;
            default:
                break;
        }
        if (view != null) {
            showPop(view);
        }
    }

    @Override
    public void result(PickSelectEntity... entity) {
        if (entity == null || entity.length == 0) {
            return;
        }
        mActivity.getEntity().getEngineeringInfoDTO().setFirstCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setFirstCategoryNo("");
        mActivity.getEntity().getEngineeringInfoDTO().setSecondCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setSecondCategoryNo("");
        mActivity.getEntity().getEngineeringInfoDTO().setThirdCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setThirdCategoryNo("");
        mActivity.getEntity().getEngineeringInfoDTO().setFourCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setFourCategoryNo("");
        mActivity.getEntity().getEngineeringInfoDTO().setFifthCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setFifthCategoryNo("");
        mActivity.getEntity().getEngineeringInfoDTO().setSixthCategoryName("");
        mActivity.getEntity().getEngineeringInfoDTO().setSixthCategoryNo("");
        int length = entity.length;
        for (int i = 0; i < length; i++) {
            switch (i) {
                case 0:
                    mActivity.getEntity().getEngineeringInfoDTO().setFirstCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setFirstCategoryNo(entity[i].getNo());
                    break;
                case 1:
                    mActivity.getEntity().getEngineeringInfoDTO().setSecondCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setSecondCategoryNo(entity[i].getNo());
                    break;
                case 2:
                    mActivity.getEntity().getEngineeringInfoDTO().setThirdCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setThirdCategoryNo(entity[i].getNo());
                    break;
                case 3:
                    mActivity.getEntity().getEngineeringInfoDTO().setFourCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setFourCategoryNo(entity[i].getNo());
                    break;
                case 4:
                    mActivity.getEntity().getEngineeringInfoDTO().setFifthCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setFifthCategoryNo(entity[i].getNo());
                    break;
                case 5:
                    mActivity.getEntity().getEngineeringInfoDTO().setSixthCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().getEngineeringInfoDTO().setSixthCategoryNo(entity[i].getNo());
                    break;
            }
        }
        mActivity.showWorkType();
    }

    @Override
    public void itemClick(String no, int position, String name) {
        if (mPopWindow.getType() < TeamMultiPopWindow.TYPE_FOU) {
            switch (mPopWindow.getType()) {
                case TeamMultiPopWindow.TYPE_TWO:
                    List<PickSelectEntity<List<PickSelectEntity>>> children = mJobData.get(mPopWindow.getPosition1()).getChildren();
                    List<PickSelectEntity> list = new ArrayList<>();
                    if (children != null && children.size() > 0) {
                        for (PickSelectEntity<List<PickSelectEntity>> mJobDatum : children) {
                            PickSelectEntity entity = new PickSelectEntity();
                            entity.setNo(mJobDatum.getNo());
                            entity.setProjectscale(mJobDatum.getProjectscale());
                            list.add(entity);
                        }
                    }
                    mPopWindow.setData2(list);
                    break;
                case TeamMultiPopWindow.TYPE_THR:
                    mPopWindow.setData3(mJobData.get(mPopWindow.getPosition1()).getChildren().get(mPopWindow.getPosition2()).getChildren());
                    break;
                default:
                    break;
            }
        }
    }

    public void showPop(View view) {
        if (mPopWindow == null) {
            getCategoryData("", view);
        } else {
            if (!mPopWindow.isShowing()) {
                mPopWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        }
    }

    // 团队规模
    public void getGm() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPackerAPI().getTeamScale(repertory.getAreaCode(), "0").enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.setGmDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //团队类型
    public void getLx() {
        List<PickSelectEntity> list = new ArrayList<>();
        PickSelectEntity pickSelectEntity1 = new PickSelectEntity();
        PickSelectEntity pickSelectEntity2 = new PickSelectEntity();
        pickSelectEntity1.setProjectscale("个人");
        pickSelectEntity1.setNo("0");
        pickSelectEntity2.setProjectscale("企业");
        pickSelectEntity2.setNo("1");
        list.add(pickSelectEntity1);
        list.add(pickSelectEntity2);
        mActivity.setLxDatas(list);
    }

    //获取经纬度信息
    public void getLocationLL() {
        DialogHelper.showProgressDialog(mActivity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(repertory.getAreaCode(), "", "", "").enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.setLocationLL(response.body().getData());
                } else {
                    MToast.showToast(mActivity, response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
            }
        });
    }

    public void getProjectTarRate() {
        DialogHelper.showProgressDialog(mActivity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().projectTarRate().enqueue(new Callback<BaseEntity<List<ProjectTarRateEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<ProjectTarRateEntity>>> call, Response<BaseEntity<List<ProjectTarRateEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.setTarRate(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<ProjectTarRateEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
            }
        });
    }

    public void uploadSingleImage(File file) {
        Map<String, RequestBody> photos = new HashMap<>();
        if (file != null) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            String fileName = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
            photos.put("file" + "\"; filename=\""+ fileName +"\"", requestBody);
        }
        DialogHelper.showProgressDialog(mActivity, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(@NonNull Call<BaseEntity> call, @NonNull Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() != null && response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.uploadImageSuccess(response.body().getData().toString());
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseEntity> call, @NonNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, "图片上传失败，请重试！");
            }
        });
    }
}
